package com.py.chat.service;

import com.py.chat.bean.Gloable;
import com.py.chat.bean.User;
import com.py.chat.dao.UserDao;
import com.py.chat.utils.PropertiesUtil;

public class UserService {

	// 加经验
	public static void addExp(User user, Integer exp) {
		Integer userLevel = user.getLevel();
		Integer userExp = user.getExp();
		// 加经验 判断是否需要升级
		int newExp = exp + userExp;
		String[] upExp = PropertiesUtil.getValue("upExp").split(",");
		int maxLevel = upExp.length;
		UserDao userDao = new UserDao();
		if (userLevel == maxLevel) {
			// 加经验
			Gloable.userMap.get(user.getId()).setExp(newExp);
			userDao.addExp(user.getId(), userLevel, newExp);
			return;
		}
		while (true) {
			if (userLevel < maxLevel && newExp >= Integer.valueOf(upExp[userLevel - 1])) {
				// 判断下一个等级需要的经验值
				newExp -= Integer.valueOf(upExp[userLevel - 1]);
				userLevel++;
			} else {
				// 反正
				userDao.addExp(user.getId(), userLevel, newExp);
				Gloable.userMap.get(user.getId()).setExp(newExp);
				Gloable.userMap.get(user.getId()).setLevel(userLevel);
				return;
			}
		}
	}

	// 判断CD是否冷却
	public static Boolean checkCD(String userId, long lastSendMsgTime) {
		int cd = Integer.valueOf(PropertiesUtil.getValue("cd")) * 60;
		UserDao userDao = new UserDao();
		// 获取上次发送的时间 如果上次发送时间为空 默认有10个技能数
		long lastTime = Gloable.userMap.get(userId).getLastSendMsgTime() / 1000; // ms
																					// ->
																					// s
		long addSkNum = 0;
		long reMainTime = 0;
		if (lastTime == 0) {
			addSkNum = 10;
		} else {
			long nowTime = System.currentTimeMillis() / 1000;
			long diff = nowTime - lastTime;
			// 现在的时间与上次发送的时间的差值除于CD时间 等于 新增技能数
			addSkNum = diff / cd;
			reMainTime = diff % cd;
		}
		// 获取技能数量
		int skNum = Gloable.userMap.get(userId).getSkNum();
		skNum += addSkNum;
		if (skNum >= 10) {
			skNum = 10;
			reMainTime = 0;
		}

		if (--skNum < 0) {
			return false;
		}
		// 更新内存 数据库 技能数量、用户最后发送消息时间
		Gloable.userMap.get(userId).setSkNum(skNum);
		Gloable.userMap.get(userId).setLastSendMsgTime(lastSendMsgTime - reMainTime);
		userDao.updateSkNumAndLastTimeById(userId, skNum, lastSendMsgTime - reMainTime);
		return true;
	}

	// 用户登陆
	public static User checkUser(String name, String password){
		// 先在userMap中查找  再数据库查找
		for (User user : Gloable.sessionMap.values()) {
			if(user.getName() == name && user.getPassword() == password ){
				return user;
			}
			if(user.getName() == name && user.getPassword() != password ){
				return null;
			}
		}
		UserDao userdao = new UserDao();
		User resultUser = userdao.checkUser(name, password);
		return resultUser;
	}
	
	public static void main(String[] args) {
		String[] upExp = PropertiesUtil.getValue("upExp").split(",");
		System.err.println(upExp.length);
	}
}
